package sf.model.fields;

import java.util.Collection;

public class TypeRegexConverter
{
	private static String datetimeRegex = "((((31\\/(0?[13578]|1[02]))|((29|30)\\/(0?[1,3-9]|1[0-2])))\\/(1[6-9]|[2-9]\\d)?\\d{2})|(29\\/0?2\\/(((1[6-9]|[2-9]\\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\\d|2[0-8])\\/((0?[1-9])|(1[0-2]))\\/((1[6-9]|[2-9]\\d)?\\d{2})) (20|21|22|23|[0-1]?\\d):[0-5]?\\d:[0-5]?\\d";

	/**
	 * Generise regex string za tip iz metasheme fizickog modela baze.
	 * 
	 * @param pdmTypeString
	 * @return
	 */
	public static String getRegex(String pdmTypeString)
	{
		StringBuffer sb = new StringBuffer();

		if (pdmTypeString.startsWith("char"))
		{
			sb.append(".{");
			int size = Integer.parseInt(pdmTypeString.substring("char("
					.length(), pdmTypeString.length() - 1));
			sb.append(size + "}");
		} else if (pdmTypeString.startsWith("varchar"))
		{
			sb.append(".{0,");
			int size = Integer.parseInt(pdmTypeString.substring("varchar("
					.length(), pdmTypeString.length() - 1));
			sb.append(size + "}");
		} else if (pdmTypeString.startsWith("int")
				|| pdmTypeString.startsWith("bigint"))
		{
			sb.append("[-+]?\\d*");
		} else if (pdmTypeString.startsWith("numeric"))
		{
			sb.append("[+-]?\\d*(\\.\\d+){0,");
			int size = Integer.parseInt(pdmTypeString.substring("numeric("
					.length(), pdmTypeString.length() - 1));
			sb.append(size + "}");
		} else if (pdmTypeString.startsWith("datetime"))
		{
			sb.append(getDatetimeRegex());
		}

		return sb.toString();
	}

	/**
	 * Generise regex string za kompozitno polje (koje se sastoji od vise kolona
	 * iz fizickog modela).
	 * 
	 * @param separator
	 * @param types
	 *            Stringovi naziva polja u fizickom modelu
	 * @return regex string
	 */
	public static String getRegexForComposite(String separator,
			Collection<String> types)
	{
		StringBuffer sb = new StringBuffer();
		int i = 0;
		for (String t : types)
		{
			sb.append(getRegex(t));
			if (i < types.size() - 1)
				sb.append(separator);
			i++;

		}

		return sb.toString();
	}

	public static String getDatetimeRegex()
	{
		return datetimeRegex;
	}

	public static synchronized void setDatetimeRegex(String datetimeRegex)
	{
		TypeRegexConverter.datetimeRegex = datetimeRegex;
	}
}
